<?php

define( "IN_ELCIUS", true );

// common functions, not specific to this application
require_once("./dependencies/functions.misc.php"); // clean()

// functions specific to this application
require_once("./dependencies/functions.common.php"); // content file stuff

// handle user request
require_once("./dependencies/class.KiwiRequest.php");
KiwiRequest::Initialize(); 
KiwiRequest::Process(); // checks if request is valid, 404, home, has access, checks skin settings, etc.




// TODO: everything below this line




// Process Request

$ctypes = array(
	"css" => "text/css",
	"js" => "application/javascript",
	"png" => "image/png",
	"gif" => "image/gif",
	"jpg" => "image/jpg",
	"jpeg" =>"image/jpg",
);


function FetchFileContents($f,$searchDirs=array("./")){
	foreach( $searchDirs as $dir ){
		if( file_exists($dir.$f) )
			return file_get_contents($dir.$f);
	}
	return false;
}
function ProcessColorMod($args,$i,$mod,$val){
	if( !isset( $args[$i] ) ) return "000000";
	if( $val == 0 ) return $args[$i];
	
	$c = str_split($args[$i],2);
	list($r,$g,$b) = array("0x".$c[0],"0x".$c[1],"0x".$c[2]);
	
	if( $mod == "+" ){
		$r = dechex(round($r+(255-$r)*$val));
		$g = dechex(round($g+(255-$g)*$val));
		$b = dechex(round($b+(255-$b)*$val));
	}
	else{
		$r = dechex(round($r+$r*(0-$val)));
		$g = dechex(round($g+$g*(0-$val)));
		$b = dechex(round($b+$b*(0-$val)));
	}
	return ("0x".$r>0xF?$r:"0".$r).("0x".$g>0xF?$g:"0".$g).("0x".$b>0xF?$b:"0".$b);
}

function ProcessDynamicCSS( &$content ){
	global $browserName;
	// drop comments and browser specific lines not for users client
	$content = preg_replace("/\/\*\*([a-z,]+)\*\*\/(.*)\n/ie","in_array('".$browserName."',explode(',','$1'))?'$2':''",$content);
	
	// locate & remove default values
	preg_match("/\/\*\*DEFAULTS:([0-F,]+)\*\*\//i",$content,$defaultArgs);
	if( !isset( $defaultArgs[1] ) ) die("/* Failed to process Dynamic CSS File: Invalid Defaults. */");
	$args = explode(",",$defaultArgs[1]);
	$content = trim(str_replace($defaultArgs[0],"",$content));
	
	// process provided values
	if( isset( $_SERVER["QUERY_PARTS"][1] ) )
		foreach( explode(",",preg_replace("/[^0-F,]/i","",$_SERVER["QUERY_PARTS"][1])) as $i => $arg )
			if( strlen($arg) == 6 )
				$args[$i] = $arg;
	
	$content = preg_replace("/\#COL([0-9]+)([\+\-])([0-9.]+)/ie","'#'.ProcessColorMod(\$args,($1)-1,'$2','$3')",$content);
	$content = preg_replace("/\#COL([0-9]+)/ie","'#'.ProcessColorMod(\$args,($1)-1,'+','0')",$content);
}


// get request type
foreach( array("css","js","img","err") as $p )
	if( isset($_GET[$p]) ) break;
if( $p == "err" ) die("Bad Request."); // bad request

// process query string
$_SERVER["QUERY_PARTS"] = explode("&",$_SERVER['QUERY_STRING']);

// get browser info
$browserInfo= null;
$browserName = "unknown";
if( preg_match_all( '#(msie|firefox|safari|webkit|opera|netscape|konqueror|gecko)[/ ]+([0-9]+(?:\.[0-9]+)?)#', strtolower($_SERVER['HTTP_USER_AGENT']), $browserInfo ) ){
	$browserName = $browserInfo[1][ count($browserInfo[1])-1 ];
}

// filter file name
preg_match("/([a-z0-9_.\-]+)\.([a-z]+)/iA",$_GET[$p],$fileNameParts);
if( !isset($fileNameParts[2]) || !isset($ctypes[$fileNameParts[2]]) ) die("Invalid File Name."); // invalid file
$fileName = $fileNameParts[0];

// fetch file contents
$content = null;
if( $p == "css" || $p == "js" ){
	$content = FetchFileContents(
		"dependencies/".$fileName,
		array(
			"./skins/".KiwiRequest::$Data['UserSkin']."/",
			"./"
		)
	);
	if( $content === false ) die(404);
	// evaluate dynamic css file
	if( strstr($fileNameParts[0], "dynamic.css") ){
		ProcessDynamicCSS($content);
	}
}
elseif( $p == "img" ){
	$content = FetchFileContents(
		$fileName,
		array(
			"./skins/".KiwiRequest::$Data['UserSkin']."/images/",
			"./images/",
			"./images/gallery/",
			"./images/videoThumbs/",
			"./images/bosses/",
		)
	);
	if( $content === false ) die(404);
}

// send content
header("Content-type: ".$ctypes[$fileNameParts[2]]);
echo $content;

?>